package buaa.qel.rpc.client.loadbalance.impl;

import buaa.qel.rpc.client.handler.RpcClientHandler;
import buaa.qel.rpc.client.loadbalance.RpcLoadBalance;
import buaa.qel.rpc.common.info.RegistryNodeInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

public class RpcLoadBalanceRandom extends RpcLoadBalance {
    private Random random = new Random();

    public RegistryNodeInfo doRoute(List<RegistryNodeInfo> addressList) {
        int size = addressList.size();
        // Random
        return addressList.get(random.nextInt(size));
    }

    /**
     * 指定一个服务（接口名+服务名）->返回一个注册信息对象（host+port+serviceList）->再通过serviceKey获取完整的服务信息包装成请求信息发送
     * serviceMap：可以知道想要的服务在哪些地址下存在
     * @param serviceKey
     * @param connectedServerNodes
     * @return
     * @throws Exception
     */
    @Override
    public RegistryNodeInfo route(String serviceKey, Map<RegistryNodeInfo, RpcClientHandler> connectedServerNodes) throws Exception {
        Map<String, List<RegistryNodeInfo>> serviceMap = getServiceMap(connectedServerNodes);
        List<RegistryNodeInfo> addressList = serviceMap.get(serviceKey);
        if (addressList != null && addressList.size() > 0) {
            return doRoute(addressList);
        } else {
            throw new Exception("Can not find connection for service: " + serviceKey);
        }
    }
}
